import 'package:flutter/material.dart';
import 'dart:math';

class LoadingAnimation extends StatefulWidget {
  const LoadingAnimation({
    super.key,
    this.color = Colors.white,
  });

  final Color color;

  @override
  State<LoadingAnimation> createState() => _LoadingAnimationState();
}

class _LoadingAnimationState extends State<LoadingAnimation> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Transform.rotate(
          angle: _controller.value * 2 * pi, // 旋转
          child: CustomPaint(
            size: const Size(28, 28),
            painter: ArcPainter(widget.color),
          ),
        );
      },
    );
  }
}

class ArcPainter extends CustomPainter {
  ArcPainter(this.color);

  final Color color;

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = color
      ..style = PaintingStyle.stroke
      ..strokeWidth = 4.0
      ..strokeCap = StrokeCap.round;

    double radius = size.width / 2;

    // 画左侧半弧
    canvas.drawArc(
      Rect.fromCircle(center: Offset(radius, radius), radius: radius),
      5 * pi / 6,
      pi / 3,
      false,
      paint,
    );

    // 画右侧半弧
    canvas.drawArc(
      Rect.fromCircle(center: Offset(radius, radius), radius: radius),
      -pi / 6,
      pi / 3,
      false,
      paint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
